# FILE: DirectionBroker.py
# DESC: provides wrapper over google direction service 
#

import urllib, sys


from web.service.WebServiceBroker import WebServiceBroker
from web.service.HttpProxyReader import HttpProxyReader
#from lbc.models import LBCategory, LBPoint


#TODO: move to oreus.conf

gmapKey = "ABQIAAAA_0hAzy4dbwijHMCZEOJ-XBStNkmczT10EsTokrjT4KAT0QQIgxRZl68X5OJEjvGyV5yLIMrI2fp0DA"

GOOGLE_DRIVING_DIRECTION_SEARCH_URL="http://maps.google.com/maps/nav?key=%s&output=json&doflg=ptj&mapclient=jsapi&q=%s&language=sk"
#GOOGLE_WALKING_DIRECTION_SEARCH_URL="http://maps.google.com/maps/nav?key=%s&output=json&mapclient=jsapi&q=%s&dirflg=w&&language=sk"
GOOGLE_WALKING_DIRECTION_SEARCH_URL="http://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&mode=walking&language=sk&region=sk&sensor=false"


G_GEO_UNKNOWN_ADDRESS = 602
G_GEO_SUCCESS = u'OK'
G_GEO_OVER_QUERY_LIMIT_ERR = u'OVER_QUERY_LIMIT'


G_TRAVEL_MODE_DRIVING = 1
G_TRAVEL_MODE_WALKING = 2


def travel_mode_to_string(travel_mode):
	rv = "unknown"
	if travel_mode == G_TRAVEL_MODE_DRIVING:
		rv = "driving"
	elif travel_mode == G_TRAVEL_MODE_WALKING:
		rv = "walking"
	return rv


class DirectionBroker(WebServiceBroker):
	def __init__(self, use_proxy = False):
		self.steps_ = []
		self.proxy_ = None
		if use_proxy:
			self.proxy_ = HttpProxyReader()


	def getDrivingDistance(self, fromPoint, toPoint):
		return self.getDistance(fromPoint.getLatLng(), toPoint.getLatLng(), G_TRAVEL_MODE_DRIVING)


	def getWalkingDistance(self, fromPoint, toPoint):
		return self.getDistance(fromPoint.getLatLng(), toPoint.getLatLng(), G_TRAVEL_MODE_WALKING)
	
			
	def getDistance(self, fromPoint, toPoint, travelMode):
		distance = None
		duration = None
		del self.steps_[:]
		
		retry = 5		
		
		print "about to send json direction request..."

		try:
			while retry > 0:
				response = None
				if travelMode == G_TRAVEL_MODE_DRIVING:
					response = self.requestJSON(GOOGLE_DRIVING_DIRECTION_SEARCH_URL % (gmapKey, urllib.quote_plus('from: %s to: %s' % (fromPoint, toPoint))), self.proxy_)
				elif travelMode == G_TRAVEL_MODE_WALKING: 
					response = self.requestJSON(GOOGLE_WALKING_DIRECTION_SEARCH_URL % (urllib.quote_plus(fromPoint), urllib.quote_plus(toPoint)), self.proxy_)
					
				print "about to process json direction response..."
				
				
					
				if response['status'] == G_GEO_SUCCESS:
					distance = response['routes'][0]['legs'][0]['distance']['value']
					duration = response['routes'][0]['legs'][0]['duration']['text']
					self.steps_ = response['routes'][0]['legs'][0]['steps']
					
					print "json direction response contains valid data"
					
					break
				elif response['status'] == G_GEO_OVER_QUERY_LIMIT_ERR:
					if not self.proxy_.renewIdentity():
						print "failed to renew identity, bailing out"
						sys.exit(-1)
					retry = retry - 1
				else:
					print 'DirectionBroker return status: %s, dont know how to proceed' % response['status']
					break
					
			if retry == 0:
				print "failed to obtain direction data"
				sys.exit(-1)
				
			print "about to print response content"	
			print "distance: %d, duration:%s\n" % (distance, duration)
			print "response content printed"
									
			return (distance, duration)
		
		except Exception, e:			
			raise e

	def getSteps(self):
		return self.steps_